package org.jeecg.modules.oauth.xkwoauth.utils;

import org.apache.commons.collections.MapUtils;

import java.util.*;

/**
 * @author: lwz
 * @description: 签名工具类
 * @since : 16:49 2018/1/10
 */
public class SignatureUtils {


    /**
     * 根据整个url地址（带参数）,生成签名
     *
     * @param url    携带参数的url地址
     * @param secret 加密秘钥
     * @return 签名字符串
     */
    public static String generateSignatureByUrl(String url, String secret) {
        int index = url.indexOf("?");
        if (index < 0) {
            return "";
        }
        String paramStr = url.substring(index + 1);
        return generateSignatureByParams(paramStr, secret);
    }

    /**
     * 根据参数字符串生成签名
     *
     * @param paramStr 格式如：a=1&b=2&c=3
     * @param secret   加密秘钥
     * @return 签名字符串
     */
    public static String generateSignatureByParams(String paramStr, String secret) {
        String[] paramKeyValues = paramStr.split("&");
        Arrays.sort(paramKeyValues);
        StringBuilder paramValueStr = new StringBuilder();
        for (String param : paramKeyValues) {
            String[] paramKeyValue = param.split("=", 2);
            paramValueStr.append(paramKeyValue[1]);
        }
        paramValueStr.append(secret);
        return AesUtils.md5(paramValueStr.toString());
    }

    /**
     * 根据SortMap类型参数和secret获取签名
     *
     * @param param
     * @param secret
     * @return
     */
    public static String generateSignature(SortedMap<String, Object> param, String secret) {
        if (MapUtils.isEmpty(param)) {
            return "";
        }
        StringBuilder paramValueStr = new StringBuilder();
        for (String item : param.keySet()) {
            paramValueStr.append(param.get(item));
        }
        paramValueStr.append(secret);
        return AesUtils.md5(paramValueStr.toString());
    }

    /**
     * 根据HashMap类型参数和secret获取签名
     *
     * @param param
     * @param secret
     * @return
     */
    public static String generateSignature(HashMap<String, Object> param, String secret) {
        if (MapUtils.isEmpty(param)) {
            return "";
        }
        SortedMap<String, Object> paramTree = new TreeMap<String, Object>(param);
        return generateSignature(paramTree, secret);
    }

    /**
     * 根据Dictionary类型参数和secret获取签名
     *
     * @param param
     * @param secret
     * @return
     */
    public static String generateSignature(Dictionary<String, Object> param, String secret) {
        if (param.isEmpty()) {
            return "";
        }
        TreeSet<String> paramSet = new TreeSet<String>();
        for (Enumeration<String> item = param.keys(); item.hasMoreElements(); ) {
            paramSet.add(item.nextElement());
        }
        StringBuilder paramValueStr = new StringBuilder();
        for (String item : paramSet) {
            paramValueStr.append(param.get(item));
        }
        paramValueStr.append(secret);
        return AesUtils.md5(paramValueStr.toString());
    }
}
